package com.snow.useviewdemo.function.phonesystem;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.text.format.Formatter;
import android.util.Log;

import com.snow.useviewdemo.R;
import com.snow.useviewdemo.base.BaseActivity;
import com.snow.useviewdemo.databinding.ActPhoneSystemParamsBinding;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * author : zyt
 * e-mail : 632105276@qq.com
 * date   : 2020-03-20
 * desc   :手机系统相关参数输出
 */
public class PhoneSystemParamsActivity extends BaseActivity<ActPhoneSystemParamsBinding> {
    StringBuffer stringBuffer;
    StringBuffer appListBuffer;

    @Override
    protected int getLayoutId() {
        return R.layout.act_phone_system_params;
    }

    @Override
    protected void setViewData(Bundle savedInstanceState) {
        stringBuffer = new StringBuffer();
        appListBuffer = new StringBuffer();
        getAppList();

        String memorySize = getAvailableInternalMemorySize(this);
        String totalInternalMemorySize = getTotalInternalMemorySize(this);
        String totalRom = getTotalRom();
        String totalRam = getTotalRam();
        StringBuilder paramsBuilder = new StringBuilder();
        paramsBuilder.append("总存储（关于手机参数标记值）：");
        paramsBuilder.append(totalRom).append("\n");
        paramsBuilder.append("总的可用存储（剔除系统固件）：");
        paramsBuilder.append(totalInternalMemorySize).append("\n");
        paramsBuilder.append("剩余存储空间：");
        paramsBuilder.append(memorySize).append("\n");
        paramsBuilder.append("总的运行内存（关于手机参数标记值）：");
        paramsBuilder.append(totalRam).append("\n");
        paramsBuilder.append("电池容量:").append(BatteryUtils.getBatteryCapacity(this)).append("mAh\n");

        paramsBuilder.append(BatteryUtils.receiverBatteryOtherInfo(this));

        mBinding.tvAppStorage.setText(paramsBuilder.toString());

        mHandler.sendEmptyMessageDelayed(3003, 5000);
    }


    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 3003:
                    String aaa = getAvailMemory(PhoneSystemParamsActivity.this);
                    String bbbb = getTotalMemory(PhoneSystemParamsActivity.this);
                    double ccccc = sampleMemory();
                    String sss = "可用内存：" + aaa + "=手机总运行内存：" + bbbb + "=当前应用需要内存：" + ccccc;
                    stringBuffer.append(sss + "\n");
                    mBinding.textView.setText(stringBuffer);
                    mHandler.sendEmptyMessageDelayed(3003, 5000);
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    /**
     * 获取手机安装应用列表
     */
    private void getAppList() {
        PackageManager pm = getPackageManager();
        // Return a List of all packages that are installed on the device.
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        int appNums = 0;
        for (PackageInfo packageInfo : packages) {
            // 判断系统/非系统应用
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) // 非系统应用
            {
                appNums++;
                appListBuffer.append("packageInfo=" + packageInfo.packageName + "\n");
                Log.e("snow", "MainActivity.getAppList, packageInfo=" + packageInfo.packageName);
            } else {
                // 系统应用
            }
        }
        String appNumsStr = "总应用数：" + packages.size() + "==非系统应用数==" + appNums + "\n";
        mBinding.appList.setText(appNumsStr + appListBuffer);
    }

    /**
     *   * 获取android当前可用运行内存大小
     *   * @param context
     *   *
     */
    public String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        // mi.availMem; 当前系统的可用内存
        return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
    }


    /**
     *   * 获取android总运行内存大小（剔除系统使用内存后的总运行内存）  与关于手机中标记参数相比较有点偏小
     *   * @param context
     *   *
     */
    public String getTotalMemory(Context context) {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            //MemTotal: 2800212 kB
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小
            arrayOfString = str2.split("\\s+");
            // 获得系统总内存，单位是KB
            long i = Long.parseLong(arrayOfString[1]);
            initial_memory = i * 1024;
            localBufferedReader.close();
        } catch (IOException e) {
        }
        return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB，内存大小规格化
    }

    /**
     * 获取当前应用使用的内存大小
     *
     * @return 单位 MB
     */
    private double sampleMemory() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        double mem = 0.0D;
        try {
            final Debug.MemoryInfo[] memInfo = activityManager.getProcessMemoryInfo(new int[]{android.os.Process.myPid()});
            if (memInfo.length > 0) {
                final int totalPss = memInfo[0].getTotalPss();
                if (totalPss >= 0) {
                    mem = totalPss / 1024.0D;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mem;
    }

    /**
     * 当前手机可用存储内存大小
     *
     * @return xx GB
     */
    public String getAvailableInternalMemorySize(Context context) {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize(context, availableBlocks * blockSize);
    }

    /**
     * 当前的手机总存储内存大小  不包含系统固件，比如手机时64G 系统固件10G，获取的结果就是54G
     *
     * @return xx GB
     */
    public String getTotalInternalMemorySize(Context context) {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return Formatter.formatFileSize(context, totalBlocks * blockSize);
    }

    /**
     * RAM内存大小, 返回1GB/2GB/3GB/4GB/8G/16G
     *
     * @return
     */
    public static String getTotalRam() {
        String path = "/proc/meminfo";
        String ramMemorySize = null;
        int totalRam = 0;
        try {
            FileReader fileReader = new FileReader(path);
            BufferedReader br = new BufferedReader(fileReader, 4096);
            ramMemorySize = br.readLine().split("\\s+")[1];
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ramMemorySize != null) {
            totalRam = (int) Math.ceil((Float.valueOf(Float.parseFloat(ramMemorySize) / (1024 * 1024)).doubleValue()));
        }

        return totalRam + "GB";
    }

    /**
     * ROM内存大小，返回 64G/128G/256G/512G
     *
     * @return
     */
    private static String getTotalRom() {
        File dataDir = Environment.getDataDirectory();
        StatFs stat = new StatFs(dataDir.getPath());
        long blockSize = stat.getBlockSizeLong();
        long totalBlocks = stat.getBlockCountLong();
        long size = totalBlocks * blockSize;
        long GB = 1024 * 1024 * 1024;
        final long[] deviceRomMemoryMap = {2 * GB, 4 * GB, 8 * GB, 16 * GB, 32 * GB, 64 * GB, 128 * GB, 256 * GB, 512 * GB, 1024 * GB, 2048 * GB};
        int i;
        for (i = 0; i < deviceRomMemoryMap.length; i++) {
            if (size <= deviceRomMemoryMap[i]) {
                break;
            }
        }
        return deviceRomMemoryMap[i] / GB + "GB";
    }
}
